package com.bizfx.component.presenters
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	import com.bizfx.component.controls.SearchField;
	import com.bizfx.component.fields.IField;
	import com.bizfx.component.views.BaseDetailView;
	import com.bizfx.component.views.IListDetailView;
	import com.bizfx.component.views.IView;
	import com.bizfx.component.views.ListDetailViewCommand;
	import com.bizfx.component.views.ViewCommand;
	import com.bizfx.errors.NoAlertError;
	import com.bizfx.events.CommonEvent;
	import com.bizfx.events.PagerEvents;
	import com.bizfx.events.SearcherEvents;
	import com.bizfx.events.ViewCommandEvent;
	import com.bizfx.events.ViewEvent;
	import com.bizfx.events.ViewValidationResultEvent;
	import com.bizfx.utils.StringUtils;
	
	import mx.collections.ArrayCollection;
	import mx.collections.IList;
	import mx.collections.SortField;
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.utils.ObjectProxy;
	
	public class BaseListDetailViewPresenter extends BasePresenter {
		
		override public function set view(value:IView):void {
			if (super.view !== value) {
				super.view = value;
				if (this.view) {
					if (thisView.listView) {
						thisView.listView.addEventListener(ViewEvent.View_Loaded, listViewLoadedHandler);
						thisView.listView.addEventListener(SearcherEvents.Searcher_DoSearch, searcherDoSearchHandler);
						thisView.listView.addEventListener(PagerEvents.PageIndex_Change, listPageIndexChangedHandler);
						thisView.listView.addEventListener(PagerEvents.PageSize_Change, listPageSizeChangedHandler);
						thisView.listView.addEventListener("listSort", listSortHandler);
					}
					if (thisView.detailView) {
						thisView.detailView.addEventListener(ViewValidationResultEvent.INVALID, detailViewValidatedHandler);
						thisView.detailView.addEventListener(ViewValidationResultEvent.VALID, detailViewValidatedHandler);
					}
					this.view.addEventListener("listViewSetted", listViewSettedHandler);
					this.view.addEventListener(ViewEvent.View_Refresh, viewRefreshHandler);			
				}
			}
		}
		
		public function BaseListDetailViewPresenter() {
			super();
		}
		
		private function get thisView():IListDetailView {
			return view as IListDetailView;
		}
		
		override protected function viewCommandRaiseHandler(event:ViewCommandEvent):void {
			this.currentViewCommand = event;
			try {
				var viewCommand:ListDetailViewCommand = (event as ViewCommandEvent).viewCommand as ListDetailViewCommand;
				
				//判断command的合法性
				switch (viewCommand.operationRecordCount) {
					case ListDetailViewCommand.OperationRecordCount_Single:
						if (!thisView.listView.selectedItem) {
							throw new Error("必须选择一条记录进行操作。");
						}
						break;
					case ListDetailViewCommand.OperationRecordCount_Multi:
						if (thisView.listView.selectedItems.length == 0) {
							throw new Error("必须选择记录进行操作。");
						}
						break;
				}
				switch (viewCommand.commandType) {
					case ListDetailViewCommand.CommandType_Add:
						this.beforeAddCommand(event);
						super.viewCommandRaiseHandler(event);
						break;
					case ListDetailViewCommand.CommandType_Edit:
						this.beforeEditCommand(event);
						super.viewCommandRaiseHandler(event);
						break;
					case ListDetailViewCommand.CommandType_View:
						this.beforeViewCommand(event);
						super.viewCommandRaiseHandler(event);
						break;
					case ListDetailViewCommand.CommandType_Background:
						this.beforeBackGroundProcessCommand(event);
						super.viewCommandRaiseHandler(event);
						break;
					case ListDetailViewCommand.CommandType_Post:
						this.beforePostCommand(event);
						break;
					case ListDetailViewCommand.CommandType_Cancel:
						this.beforeCancelCommand(event);
						super.viewCommandRaiseHandler(event);
						break;
					default:
						super.viewCommandRaiseHandler(event);
						break;
				}
			} catch (e:NoAlertError) {
			} catch (e:Error) {
				logger.warn(e.message);
				Alert.show(e.message, "错 误");
			}
		}
				
		protected function beforeAddCommand(event:ViewCommandEvent):void {
			showDetailView(false, BaseDetailView.DetailViewStatus_New, event.viewCommand.commandKey);
			thisView.listView.selectedItem = null;
			this.initDetialDatas();
		}
		protected function beforeEditCommand(event:ViewCommandEvent):void {
			showDetailView(false, BaseDetailView.DetailViewStatus_Edit, event.viewCommand.commandKey);
			this.initDetialDatas();
		}
		protected function beforeViewCommand(event:ViewCommandEvent):void {
			showDetailView(true, BaseDetailView.DetailViewStatus_View, event.viewCommand.commandKey);
			this.initDetialDatas();
		}
		private function initDetialDatas():void {
			if (thisView.detailView.needInit) {
				this.loadInitDetailViewData();
			} else {
				thisView.detailView.viewDataSource = this.getNewDetailViewDataSource();
				if (thisView.listView.selectedItem) {
					this.loadDetailViewData(thisView.listView.selectedItem);
				}
			}
		}
		protected function beforePostCommand(event:ViewCommandEvent):void {
			thisView.detailView.validate();
		}
		protected function beforeCancelCommand(event:ViewCommandEvent):void {
			showListView(false);
		}
		protected function beforeBackGroundProcessCommand(event:ViewCommandEvent):void {
		}
		
		protected function loadInitDetailViewData():void {
			this.thisView.detailView.initData = new ObjectProxy(new Object());
		}
		
		protected function showDetailView(readOnly:Boolean, viewStatus:String, viewEventKey:String):void {
			thisView.listView.hide();
			thisView.detailView.show();
			thisView.detailView.readOnly = readOnly;
			thisView.detailView.status = viewStatus;
			thisView.detailView.hideAllViewCommands();
			thisView.detailView.refresh();
			var commands:IList = thisView.getListDetailCommands(viewEventKey) as IList;
			for (var i:int; i < commands.length; i++) {
				thisView.detailView.showViewCommand(commands[i].toString());
			}
		}
		
		protected function showListView(readOnly:Boolean):void {
			thisView.listView.show();
			thisView.detailView.hide();
			//把明细页面清空
			this.thisView.detailView.viewDataSource = new ObjectProxy(new Object());
		}
		
		protected function getNewDetailViewDataSource():Object {
			return new ObjectProxy(new Object());
		}
		
		protected function loadListViewData(pageIndex:int = 1):void {
		}
		
		protected function loadDetailViewData(selectedItem:Object):void {
		}
		/**
		 * Event Handler
		 */
		
		public function listViewLoadedHandler(event:ViewEvent):void {
			thisView.listView.viewDataSource = null;
			this.loadListViewData(1);
		}
		
		protected function loadListViewDataResponseHandler(event:ResultEvent):void {
			if (event.result != null && event.result.success) {
				this.thisView.listView.viewDataSource = event.result.data;
			} else {
				Alert.show(event.result.errorMessage, "错 误");
			}
		}
		
		protected function loadDetailViewDataResponseHandler(event:ResultEvent):void {
			if (event.result != null && event.result.success) {
				this.thisView.detailView.viewDataSource = event.result.entity;
			} else {
				Alert.show(event.result.errorMessage, "错 误");
			}
		}
		
		protected function faultResponseHandler(event:FaultEvent):void {
			Alert.show(event.message.toString(), "错 误");
		}
		
		protected function listEditCommandResponseHandler(event:ResultEvent):void {
			if (event.result.success) {
				thisView.listView.viewDataSource = null;
				this.loadListViewData(this.thisView.listView.pageIndex);
				this.showListView(false);
			} else {
				Alert.show(event.result.errorMessage, "错 误");
			}
		}
		
		protected function listAddCommandResponseHandler(event:ResultEvent):void {
			if (event.result.success) {
				thisView.listView.viewDataSource = null;
				this.loadListViewData(this.thisView.listView.pageIndex);
				this.showListView(false);
			} else {
				Alert.show(event.result.errorMessage, "错 误");
			}
		}
		
		protected function listBackGroundProcessCommandResponseHandler(event:ResultEvent):void {
			if (event.result.success) {
				thisView.listView.viewDataSource = null;
				this.loadListViewData(this.thisView.listView.pageIndex);
			} else {
				Alert.show(event.result.errorMessage, "错 误");
			}
		}
		
		protected function loadInitDetailViewDataResponseHandler(event:ResultEvent):void {
			thisView.detailView.initData = event.result;
			thisView.detailView.viewDataSource = this.getNewDetailViewDataSource();
			if (thisView.listView.selectedItem) {
				this.loadDetailViewData(thisView.listView.selectedItem);
			}
		}
		
		private function searcherDoSearchHandler(event:CommonEvent):void {
			this.loadListViewData(1);
		}
		
		private function listPageIndexChangedHandler(event:CommonEvent):void {
			this.loadListViewData(this.thisView.listView.pageIndex);
		}	
		
		private function listPageSizeChangedHandler(event:CommonEvent):void {
			this.loadListViewData(this.thisView.listView.pageIndex);
		}
		
		private function listSortHandler(event:CommonEvent):void {
			this.loadListViewData(this.thisView.listView.pageIndex);
		}
		
		protected function listViewSettedHandler(event:Event):void {
			if (thisView.listView) {
				thisView.listView.addEventListener(ViewEvent.View_Loaded, listViewLoadedHandler);
				thisView.listView.addEventListener(SearcherEvents.Searcher_DoSearch, searcherDoSearchHandler);
				thisView.listView.addEventListener(PagerEvents.PageIndex_Change, listPageIndexChangedHandler);
				thisView.listView.addEventListener(PagerEvents.PageSize_Change, listPageSizeChangedHandler);
				thisView.listView.addEventListener("listSort", listSortHandler);
			}
			if (thisView.detailView) {
				thisView.detailView.addEventListener(ViewValidationResultEvent.INVALID, detailViewValidatedHandler);
				thisView.detailView.addEventListener(ViewValidationResultEvent.VALID, detailViewValidatedHandler);
			}
		}
		
		protected function viewRefreshHandler(event:Event):void {
			this.thisView.listView.refresh();
			this.thisView.detailView.refresh();
			this.thisView.listView.show();
			this.thisView.detailView.hide();
		}
		
		private function detailViewValidatedHandler(event:ViewValidationResultEvent):void {
			if (event.type == ViewValidationResultEvent.VALID) {
				super.viewCommandRaiseHandler(this.currentViewCommand);
			}
		}
	}
}